/*
Roept aan: /ajax/findPlayer.php?query=fl

Wilt JSON terugkrijgen:
{
  "results": 
  [
    {
      "URL": "/spelers/1121",
      "Name": "Florian Zoet"
    },
    {
      "URL": "/teams/1204",
      "Name": "Floorball Flames<br />Heren Floorball Competitie"
    }
  ]
}

Of bij geen resultaat:
{
  "results":
  [ ]
}
*/

var suggestQuery = '';
var suggestLoaded = 'no';
var suggestObject;
function autoComplete(query) {
	suggestQuery = query;
	if(suggestQuery.length > 1) {
		if(suggestLoaded == 'yes') {
			doMatch();
		}
		if(suggestLoaded == 'busy') {
			// niks doen
		}
		if(suggestLoaded == 'no') {
			suggestLoaded = 'busy';
			$('#suggest').html('<p class="laden">Spelers zoeken...</p>').show();
			$.ajax({
				url: '/ajax/findPlayer.php?query='+query.substr(0,2),
				success: function(data) {
					suggestObject = jQuery.parseJSON(data);
					suggestLoaded = 'yes';
					doMatch();
				},
				error: function(request, status, error) {
					$('#suggest').html('<p><strong>Oeps.</strong> Er ging iets mis bij het zoeken naar spelers. Heb je verbinding met internet?</p>');
					suggestLoaded = 'no';
				}
			});
		}
	} else {
		suggestLoaded = 'no';
		$('#suggest').html('');
	}
}
function doMatch() {
	var numMatches = 0;
	var output = '<table>';
	$(suggestObject.results).each(function() {
		if(this.Name.search(new RegExp(suggestQuery, 'i')) > -1) {
			output += '<tr><td><a href="'+this.URL+'">'+this.Name+'</a></td></tr>';
			numMatches++;
		}
	});
	if(numMatches == 0) {
		output += '<tr><td>Geen spelers gevonden voor '+suggestQuery+'</td></tr>';
	}
	output += '</table>';
	$('#suggest').html(output);
}